package org.micode.common.utils;

import org.micode.common.exception.DataException;
import org.micode.common.exception.VerifyFailException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 加密相关的工具
 */
@Slf4j
public class EncryptUtils {

    static final String DES = "DES";

    static String charset = "utf-8";

    static int keySizeDES = 0;

    /**
     * 获取密文
     */
    public static String getCipherText(String plaintext, String key)
            throws NoSuchAlgorithmException {
        if (null == plaintext || null == key) {
            throw new DataException("Invalid arg");
        }

        String s_pwd = MD5Utils.getMD5(plaintext).toLowerCase();
        String s_pwdAndNo = MD5Utils.getMD5(s_pwd + key);
        return s_pwdAndNo.toUpperCase();
    }

    /**
     * 获取密文
     */
    public static String getSha256CipherText(String plaintext, String salt) {
        if (null == plaintext || null == salt) {
            throw new DataException("Invalid arg");
        }

        return new Sha256Hash(plaintext, salt).toHex();
    }

    /**
     * 使用DES加密算法进行加密(可逆)
     *
     * @param res 需要加密的原文
     * @param key 秘钥
     * @return
     */
    public static String DESencode(String res, String key) {
        return keyGeneratorES(res, DES, key, keySizeDES, true);
    }

    /**
     * 对使用DES加密算法的密文进行解密(可逆)
     *
     * @param res 需要解密的密文
     * @param key 秘钥
     * @return
     */
    public static String DESdecode(String res, String key) {
        return keyGeneratorES(res, DES, key, keySizeDES, false);
    }

    /**
     * 使用KeyGenerator双向加密，DES/AES，注意这里转化为字符串的时候是将2进制转为16进制格式的字符串，不是直接转，因为会出错
     *
     * @param res       加密的原文
     * @param algorithm 加密使用的算法名称
     * @param key       加密的秘钥
     * @param keySize
     * @param isEncode
     * @return
     */
    private static String keyGeneratorES(String res, String algorithm, String key, int keySize, boolean isEncode) {
        try {
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            if (keySize == 0) {
                byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
                kg.init(new SecureRandom(keyBytes));
            } else if (key == null) {
                kg.init(keySize);
            } else {
                byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset);
                kg.init(keySize, new SecureRandom(keyBytes));
            }
            SecretKey sk = kg.generateKey();
            SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            if (isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset);
                return parseByte2HexStr(cipher.doFinal(resBytes));
            } else {
                cipher.init(Cipher.DECRYPT_MODE, sks);
                return new String(cipher.doFinal(parseHexStr2Byte(res)));
            }
        } catch (Exception e) {
            log.warn("keyGeneratorES() call failed, {}", e.getMessage());
        }
        return null;
    }

    /**将二进制转换成16进制 */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**将16进制转换为二进制*/
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
//        System.out.println(getCipherText("18923714596", "612345678912345605"));
//        System.out.println(getSha256CipherText("1234567890", "YzcmCZNvbXocrsz9dm8e"));
//        System.out.println(getSha256CipherText("1234567890", "hgoku7oEhvjoqqutHmS4"));
        System.out.println(getSha256CipherText("18923714596", "3"));
    }

}
